/**
 * 页面参数Hook
 */
import { ref, onMounted } from 'vue';
import Taro from '@tarojs/taro';

export function usePageParams<T extends Record<string, any> = Record<string, string>>() {
  const params = ref<T>({} as T);
  const loaded = ref(false);

  onMounted(() => {
    // 获取当前页面实例
    const pages = Taro.getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const query = currentPage?.query || {};

    // 将参数转换为正确的类型
    const result = {} as T;
    Object.keys(query).forEach(key => {
      const value = query[key];

      // 尝试将数值字符串转为数值
      if (/^-?\d+$/.test(value)) {
        result[key as keyof T] = parseInt(value, 10) as any;
      } else if (/^-?\d+\.\d+$/.test(value)) {
        result[key as keyof T] = parseFloat(value) as any;
      } else if (value === 'true') {
        result[key as keyof T] = true as any;
      } else if (value === 'false') {
        result[key as keyof T] = false as any;
      } else {
        result[key as keyof T] = value as any;
      }
    });

    params.value = result;
    loaded.value = true;
  });

  return {
    params,
    loaded,
  };
}
